package com.zhiyume.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhiyume.dto.BaseResponse;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Map;

public class BaseController {
    @Value("${custom.domain.path}")
    private String domainPath;
    @Value("${custom.domain.domain}")
    private String domainDomain;
    @Value("${custom.domain.baseUrl}")
    private String baseUrl;

    public void addCookies(HttpServletResponse response, Map<String, Object> cookies, String domain) {
        for (String key : cookies.keySet()) {
            Cookie cookie = new Cookie(key, String.valueOf(cookies.get(key)));
            cookie.setPath(domainPath);
            if (domain != null) {
                cookie.setDomain(domain);
            } else {
                cookie.setDomain(domainDomain);
            }
            response.addCookie(cookie);
            response.setHeader("P3P",
                    "CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"");
        }
    }

    public String getCookie(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return "";
    }

    // 清除cookies
    protected void delCookies(HttpServletResponse response, String[] cookies, String domain) {
        for (String c : cookies) {
            Cookie cookie = new Cookie(c, null);
            cookie.setPath(domainPath);
            cookie.setMaxAge(0);
            if (domain != null) {
                cookie.setDomain(domain);
            } else {
                cookie.setDomain(domainDomain);
            }
            response.addCookie(cookie);
            response.setHeader("P3P",
                    "CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"");
        }
    }

    protected void responseJsonStr(HttpServletResponse response, BaseResponse baseResDTO) {
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        Writer writer = null;
        try {
            writer = response.getWriter();
            String jsonObject = JSONObject.toJSONString(baseResDTO);
            writer.write(jsonObject);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    protected String getRequesetUrl() {
        return baseUrl;
    }

    public static String httpGet(String url) throws IOException {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string(); // 返回的是string 类型，json的mapper可以直接处理
    }

    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    public static String httpPost(String url, String json) throws IOException {
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    protected String formatParam(Object object) {
        try {
            StringBuffer sb = new StringBuffer();
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if (propertyDescriptors != null) {
                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    Object propertyValue = propertyDescriptor.getReadMethod().invoke(object);
                    if (propertyValue != null && !"class".equals(propertyDescriptor.getName())) {
                        if (sb.length() > 0) {
                            sb.append("&");
                        } else {
                            sb.append("?");
                        }
                        sb.append(propertyDescriptor.getName())
                                .append("=")
                                .append(URLEncoder.encode(propertyValue.toString(), "utf-8"));
                    }
                }
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
      //  String url = "http://login.xinhua-news.com/login/loginSSO.action?username=jill1&password=123456";
        //String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=wxc1cc4dec47a0f1a4&grant_type=refresh_token&refresh_token=4_FXUIl8X7-YgeNC8p7UJkxUeZDsS3c04p17kM2I6iLCwAHyqQkHSN6YyLx2a8Ik5n1bnrpOoif5SYT4yBKl9qaVWHGZLWjZfbJZpIs83diuc";
        String url = "http://q.qlogo.cn/qqapp/215464/F72DA273B93CD84750B75423A24FC289/40";
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        System.out.println(response.header("Content-Type"));
        //System.out.println(httpGet(url));
    }
}
